﻿@page "/agentadd"
@using Gurux.DLMS.AMI.Module
@using Gurux.DLMS.AMI.Shared
@using Gurux.DLMS.AMI.Shared.DIs
@using Gurux.DLMS.AMI.Shared.Enums
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@using Gurux.DLMS.AMI.Shared.DTOs
@using Gurux.DLMS.AMI.Shared.Rest
@using Microsoft.AspNetCore.SignalR.Client
@using Gurux.DLMS.AMI.Client.Pages.Agent
@using System.Text.Json

@attribute [Authorize(Roles = "Admin, AgentManager")]
@inject NavigationManager NavigationManager
@inject HttpClient Http
@inject IGXNotifier Notifier

<h1>配置账户</h1>
配置说明参见 <a target="_blank" href="https://www.gurux.fi/agent-configure">文档</a>.

<EditForm Model="@this">
    <DataAnnotationsValidator />
    <ValidationSummary />
    <button class="btn btn-secondary" @onclick="OnDownload">
        <div class="oi oi-data-transfer-download"></div>
        &nbsp;@Properties.Resources.DownloadAgent
    </button>
    <p>
        <hr />
    </p>
    <div class="form-group">
        <label>@Properties.Resources.Name</label>
        <InputText id="token" class="form-control" @bind-Value="TokenName" />
    </div>
    <div class="form-group">
        <label>@Properties.Resources.Expiration</label>
        <InputDate Type="@InputDateType.DateTimeLocal" id="expiration" class="form-control"
                   @bind-Value="TokenExpiration" />
    </div>
    <button class="btn btn-secondary" @onclick="OnToken">
        <div class="oi oi-key"></div>
        &nbsp;@Properties.Resources.GenerateAccessToken
    </button>
    @if (Token != null)
    {
        <div class="form-group">
            <label>@Properties.Resources.TokensTitle</label>
            <InputText id="token" class="form-control" readonly="readonly"
                   @bind-Value="Token" />
        </div>
        <p>
            <div style="background: #f4e8d6; padding: 1.25rem 1.25rem 1.25rem 1.25rem; ">
                <p>
                    @Properties.Resources.AgentTokenCreateSucceeded
                </p>
            </div>
        </p>
    }
</EditForm>
@code {
    [Inject]
    public IJSRuntime JSRuntime { get; set; }
    //Token expiration time.
    public DateTimeOffset? TokenExpiration
    {
        get;
        set;
    }

    //Generated token.
    public string TokenName { get; set; } = "Generated";

    //Generated token.
    public string? Token
    {
        get;
        set;
    }

    /// <summary>
    /// Download the latest agent.
    /// </summary>
    public async void OnDownload()
    {
        try
        {
            DownloadAgent req = new DownloadAgent();
            var ret = await Http.PostAsJson<DownloadAgentResponse>("api/Agent/Download", req);
            string? url = ret.Urls.FirstOrDefault();
            IJSObjectReference module = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./download.js");
            await module.InvokeVoidAsync("saveFile", url);
        }
        catch (Exception ex)
        {
            Notifier?.ProcessError(ex);
        }
        finally
        {
            Notifier?.ProgressEnd();
        }
    }

    /// <summary>
    /// Generate new token.
    /// </summary>
    public async void OnToken()
    {
        Notifier?.ProgressStart();
        Notifier?.ClearStatus();
        try
        {
            GXPersonalToken token = new GXPersonalToken();
            token.Name = TokenName;
            token.Expiration = TokenExpiration;
            token.Scopes = new string[] { "agent.view","agent.add", "agent.edit",
            "task.view", "task.edit", "object.edit",
            "device.view", "device.add","device-error.add",
            "agent-log.add", "device-trace.add",
            "device-action.add", "value.add", "attribute.edit", 
            "script.view", 
            "script-log.add",
            "key-management.view",
            "gateway.view","gateway.add",
            "gateway-log.add"
            };
            UpdateToken req = new UpdateToken() { Tokens = new GXPersonalToken[] { token } };
            var ret = await Http.PostAsJson<UpdateTokenResponse>("api/Token/Add", req);
            Token = ret.Token;
            StateHasChanged();
        }
        catch (Exception ex)
        {
            Notifier?.ProcessError(ex);
        }
        finally
        {
            Notifier?.ProgressEnd();
        }
    }

    protected override void OnInitialized()
    {
        try
        {
            if (Notifier == null)
            {
                throw new ArgumentException(Properties.Resources.InvalidNotifier);
            }
            Notifier.ClearStatus();
            Notifier.Clear();
            Notifier.AddMenuItem(new GXMenuItem() { Text = Properties.Resources.Close, Icon = "oi oi-action-undo", OnClick = OnCancel });
            Notifier.UpdateButtons();
        }
        catch (AccessTokenNotAvailableException exception)
        {
            exception.Redirect();
        }
        catch (Exception ex)
        {
            Notifier?.ProcessError(ex);
        }
    }

    /// <summary>
    /// Cancel update.
    /// </summary>
    private void OnCancel()
    {
        ClientHelpers.NavigateToLastPage(NavigationManager, Notifier);
    }
}
